package com.google.samples.apps.room

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.samples.apps.library_common.base.BaseAdapter
import com.google.samples.apps.library_common.utils.LogUtils
import com.google.samples.apps.room.data.User
import com.google.samples.apps.room.data.UserDatabase
import com.google.samples.apps.room.data.UserViewModel
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    var userAdapter: BaseAdapter<User>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val userViewModel = ViewModelProvider(this)
            .get(UserViewModel::class.java)
        val userDatabase = UserDatabase.getInstance(this)

        btnAdd.setOnClickListener {
            userDatabase.userDao().insertUser(
                User(5, "歌手", 45)
            )
        }

        btnQuery.setOnClickListener {
            LogUtils.d()
            LogUtils.d(userDatabase.userDao().getUserById(1))
        }

        btnDelete.setOnClickListener {
            userDatabase.userDao().deleteUser(userDatabase.userDao().getUserById(5))
        }

        recyclerView.run {
            layoutManager = LinearLayoutManager(context)
            userAdapter = object : BaseAdapter<User>(R.layout.item_user) {
                override fun convert(holder: BaseViewHolder, item: User) {
                    holder.setText(R.id.text, item.toString())
                }
            }
            adapter = userAdapter
        }

        userViewModel.getLiveDataUser(this).observe(this, Observer {
            userAdapter?.setList(it)
        })
        LogUtils.d()
    }
}